package com.ouyunc.file.plugins.base;

import cn.hutool.core.util.ClassUtil;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.ouyunc.common.constant.enums.FilePluginEnum;
import com.ouyunc.file.plugins.AbstractUploaderDownloader;
import com.ouyunc.file.plugins.Downloader;
import com.ouyunc.file.plugins.Uploader;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;
import java.util.Map;
import java.util.Set;

/**
 * @Author fangzhenxun
 * @Description: 返回上传或下载接口
 * @Version V1.0
 **/
public class FileContextHolder {

    //使用缓存保证单例
    private static LoadingCache<FilePluginEnum, AbstractUploaderDownloader> uploaderDownloaderLoadingCache = Caffeine.newBuilder().build(new CacheLoader() {
        @Nullable
        @Override
        public Object load(@NonNull Object o) throws Exception {
            return null;
        }

        @Override
        public @NonNull Map loadAll(@NonNull Iterable keys) throws Exception {
            return null;
        }
    });




    private FileContextHolder() {
    }

    // 初始化数据
    static {
        Objenesis objenesis = new ObjenesisStd(true);
        Set<Class<?>> uploaderAndDownloaderClassList = ClassUtil.scanPackageBySuper(AbstractUploaderDownloader.class.getPackage().getName(), AbstractUploaderDownloader.class);
        uploaderAndDownloaderClassList.forEach(uploaderAndDownloaderClass ->{
            AbstractUploaderDownloader uploaderDownloader = (AbstractUploaderDownloader)objenesis.newInstance(uploaderAndDownloaderClass);
            uploaderDownloaderLoadingCache.put(uploaderDownloader.pluginEnum(), uploaderDownloader);
        });
    }


    /**
     * @Author fangzhenxun
     * @Description 获取上传接口插件
     * @param
     * @return com.ouyunc.common.plugins.file.Uploader
     */
    public static Uploader uploader(FilePluginEnum pluginEnum) {
        return uploaderDownloaderLoadingCache.get(pluginEnum);
    }

    /**
     * @Author fangzhenxun
     * @Description 获取下载接口插件
     * @param
     * @return com.ouyunc.common.plugins.file.Downloader
     */
    public static Downloader downloader(FilePluginEnum pluginEnum) {
        return uploaderDownloaderLoadingCache.get(pluginEnum);
    }


}
